import Vue from 'vue';
import Router from 'vue-router';
import NProgress from 'nprogress';
import permission from './permission';
import store from '../store/';
import { clearHttpRequestingList } from '@http/httpRequestList';
import routes from './routes';

Vue.$httpRequestList = [];
Vue.use(Router);

let router = new Router({
  routes,
});
// 路由的前置守卫，判断是否有权限访问
router.beforeEach((to, from, next) => {
  console.log('路由跳转前置守卫');
  if (to.meta.keepAlive) {
    store.commit('routecache/keepAlive', to.name);
  }
  clearHttpRequestingList();
  NProgress.start();

  console.log(from.name);
  console.log(to.name);

  const whiteList = store.getters['permission/getWhiteList'];
  if (whiteList.indexOf(to.name) > -1 || whiteList.indexOf(to.path) > -1) {
    store.commit('user/SET_USER_ID', localStorage.getItem('id'));
    store.commit('user/SET_USER_NAME', localStorage.getItem('name'));
    store.commit('user/SET_USER_TYPE', localStorage.getItem('type'));
    console.log('访问的页面在白名单中');
    next();
  } else if (!store.getters['user/getUserId']) {
    if (localStorage.getItem('id')) {
      console.log('用户刷新x`x`了界面');
      store.commit('user/SET_USER_ID', localStorage.getItem('id'));
      store.commit('user/SET_USER_NAME', localStorage.getItem('name'));
      store.commit('user/SET_USER_TYPE', localStorage.getItem('type'));
      permission(store, routes, to, next);
    } else {
      console.log('用户未登录');
      next({ name: 'login' });
    }
    // break;
    //     }
    //   }
    // });
  } else {
    // 权限校验
    console.log('用户请求跳转');

    permission(store, routes, to, next);
  }
  console.log('路由跳转前置守卫结束');
});
router.afterEach(() => {
  NProgress.done();
});
export default router;
